using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Razor.TagHelpers;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace ReaWTM.LayuiHelper
{
	public enum UploadTypeEnum { AllFiles, ImageFile, ZipFile, ExcelFile, WordFile, PDFFile, TextFile }

	[HtmlTargetElement("wt:upload", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.WithoutEndTag)]
	public class UploadTagHelper : BaseFieldTag
	{

		/// <summary>
		/// 限定上传文件大小，单位K
		/// </summary>
		public int FileSize { get; set; }

		/// <summary>
		/// 上传文件类别
		/// </summary>
		public UploadTypeEnum UploadType { get; set; }

		/// <summary>
		/// 是否显示进度条，默认为false
		/// </summary>
		public bool? ShowProgress { get; set; }

		/// <summary>
		/// 当上传文件类别为ImageFile时，指定缩小的宽度，框架会使用缩小后的图片保存
		/// </summary>
		public int? ThumbWidth { get; set; }

		/// <summary>
		/// 当上传文件类别为ImageFile时，指定缩小的高度，框架会使用缩小后的图片保存
		/// </summary>
		public int? ThumbHeight { get; set; }

		/// <summary>
		/// 是否使用缩略图预览，当上传文件类别为ImageFile时，默认为true
		/// </summary>
		public bool? ShowPreview { get; set; }

		/// <summary>
		/// 如果使用缩略图预览，指定缩略图宽度，默认64
		/// </summary>
		public int? PreviewWidth { get; set; }

		/// <summary>
		/// 如果使用缩略图预览，指定缩略图高度，默认64
		/// </summary>
		public int? PreviewHeight { get; set; }

		public string CustomType { get; set; }

		public string ConnectionString { get; set; }

		public string ButtonText { get; set; }

		public string UploadGroupName { get; set; }
		public string UploadSubdir { get; set; }
		public string UploadMode { get; set; }
		public string ExtraQuery { get; set; }

		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			output.Attributes.Add("id", Id + "button");
			output.Attributes.Add("name", Id + "button");
			output.TagMode = TagMode.StartTagAndEndTag;

			var vm = context.Items["model"] as BaseVM;
			var url = "/_Framework/Upload?1=1";

			if (string.IsNullOrEmpty(ConnectionString) == true)
			{
				if (vm != null)
				{
					url = url.AppendQuery($"_DONOT_USE_CS={vm.CurrentCS}");
				}
			}
			else
			{
				url = url.AppendQuery($"_DONOT_USE_CS={ConnectionString}");
			}
			if (string.IsNullOrEmpty(UploadGroupName) == false)
			{
				url = url.AppendQuery($"groupName={UploadGroupName}");
			}
			if (string.IsNullOrEmpty(UploadSubdir) == false)
			{
				url = url.AppendQuery($"subdir={UploadSubdir}");
			}
			if (string.IsNullOrEmpty(UploadMode) == false)
			{
				url = url.AppendQuery($"sm={UploadMode}");
			}

			url = url.AppendQuery(ExtraQuery);

			if (UploadType == UploadTypeEnum.ImageFile)
			{
				if (ShowPreview == null || ShowPreview == true)
				{
					ShowPreview = true;
					if (PreviewWidth == null && PreviewHeight == null)
					{
						PreviewHeight = 64;
						PreviewWidth = 64;
					}
					var text = "点击上传，或将文件拖拽到此处";
					if (!string.IsNullOrEmpty(ButtonText))
					{
						text = ButtonText;
					}

					output.TagName = "div";
					output.Attributes.Add("class", "layui-upload-drag wtm-upload-drag");
					output.Content.AppendHtml($"<i class='layui-icon layui-icon-upload'><p class='layui-font-12'>{text}</p></i>");
					output.PostElement.AppendHtml($@"<div id='{Id}div'/>");
				}

				url = "/_Framework/UploadImage?1=1";
				if (ThumbWidth != null)
				{
					url += "&width=" + ThumbWidth;
				}
				if (ThumbHeight != null)
				{
					url += "&height=" + ThumbHeight;
				}
			}
			else
			{
				output.TagName = "button";
				output.Attributes.Add("class", "layui-btn layui-btn-normal wtm-upload-btn");
				output.Attributes.Add("type", "button");
				output.PostElement.AppendHtml($@"<span id='{Id}div'></span>");
				if (string.IsNullOrEmpty(ButtonText))
				{
					output.Content.SetHtmlContent(THProgram._localizer["Sys.Select"]);
				}
				else
				{
					output.Content.SetHtmlContent(ButtonText);
				}
			}



			if (Disabled == true)
			{
				output.Attributes.Add("style", "display:none");
			}

			string ext = "";
			if (string.IsNullOrEmpty(CustomType))
			{
				switch (UploadType)
				{
					case UploadTypeEnum.AllFiles:
						ext = "";
						break;
					case UploadTypeEnum.ImageFile:
						ext = "jpg|jpeg|gif|bmp|png|tif";
						break;
					case UploadTypeEnum.ZipFile:
						ext = "zip";
						break;
					case UploadTypeEnum.ExcelFile:
						ext = "xls|xlsx";
						break;
					case UploadTypeEnum.PDFFile:
						ext = "pdf";
						break;
					case UploadTypeEnum.WordFile:
						ext = "doc|docx";
						break;
					case UploadTypeEnum.TextFile:
						ext = "txt";
						break;
				}
			}
			else
			{
				ext = CustomType;
			}


			var requiredtext = "";
			if (Field.Metadata.IsRequired || Required == true)
			{
				requiredtext = $" lay-verify='required' lay-reqText='{THProgram._localizer["Validate.{0}required", Field?.Metadata?.DisplayName ?? Field?.Metadata?.Name]}'";
			}

			output.PostElement.AppendHtml($@"<input hidden id='{Id}' name='{Field.Name}' value='{Field.Model}' {requiredtext} />");
			if (ShowProgress != null)
			{
				if (ShowProgress == true)
				{
					output.PostElement.AppendHtml($@"
<div class='layui-progress' lay-showpercent='true' lay-filter='demo'>
    <div class='layui-progress-bar layui-bg-red' lay-percent='0%'></div>
</div>
");
				}
			}
			output.PostElement.AppendHtml($@"
<script>
wtm.upload_Render({{
{(PreviewHeight == null ? "" : $"previewHeight:{PreviewHeight},")}
{(PreviewWidth == null ? "" : $"previewWidth:{PreviewWidth},")}
{(ShowPreview == null ? "" : $"showPreview:{ShowPreview.ToString().ToLower()},")}
cs:'{(vm != null ? vm.CurrentCS : "")}',
disabled:{Disabled.ToString().ToLower()},
ext:'{ext}',
fileSize:{FileSize},
id:'{Id}',
sysDelete:'{THProgram._localizer["Sys.Delete"]}',
sysUploadFailed:'{THProgram._localizer["Sys.UploadFailed"]}',
url:'{url}',
beforeMount:'{BeforeMount}',
mounted:'{Mounted}',
}});
</script>
".Replace("\r\n", ""));

			if (Field.Model != null && Field.Model.ToString() != Guid.Empty.ToString())
			{
				var geturl = $"/_Framework/GetFileName/{Field.Model}";
				var downloadurl = $"/_Framework/GetFile/{Field.Model}";
				if (vm != null)
				{
					geturl += $"?_DONOT_USE_CS={vm.CurrentCS}";
					downloadurl += $"?_DONOT_USE_CS={vm.CurrentCS}";
				}
				var picurl = $"/_Framework/GetFile?id={Field.Model}&stream=true&width={PreviewWidth}&height={PreviewHeight}";
				if (vm != null)
				{
					picurl += $"&_DONOT_USE_CS={vm.CurrentCS}";
				}
				output.PostElement.AppendHtml($@"
<script>
wtm.upload_AjaxGet({{
{(PreviewHeight == null ? "" : $"previewHeight:{PreviewHeight},")}
{(PreviewWidth == null ? "" : $"previewWidth:{PreviewWidth},")}
{(ShowPreview == null ? "" : $"showPreview:{ShowPreview.ToString().ToLower()},")}
cs:'{(vm != null ? vm.CurrentCS : "")}',
disabled:{Disabled.ToString().ToLower()},
downloadurl:'{downloadurl}',
fileId:'{Field.Model}',
geturl:'{geturl}',
id:'{Id}',
picurl:'{picurl}',
sysDelete:'{THProgram._localizer["Sys.Delete"]}',
}});
</script>
".Replace("\r\n", ""));
			}

			base.Process(context, output);

		}

		protected override void SetRequired(TagHelperOutput output)
		{
			throw new NotImplementedException();
		}
	}
}
